package com.tchintech.pay.utils;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.tchintech.pay.MyApplication;
import com.tchintech.pay.view.activity.LoginActivity;

/**
 * <Pre>
 * 用来捕捉崩溃异常的句柄
 * </Pre>
 *
 * @author John
 * @version 1.0
 *          <p/>
 *          Create by 2016/3/21 11:38
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private final String TAG = CrashHandler.class.getSimpleName();

    private static Thread.UncaughtExceptionHandler defaultHandler = null;

    private MyApplication context = null;
    //CrashHandler实例
    private static CrashHandler INSTANCE = new CrashHandler();
    // 用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();

    public CrashHandler(MyApplication context) {
        this.context = context;
    }

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化,设置该CrashHandler为程序的默认处理器
     */
    public static void init(CrashHandler crashHandler) {
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    }


    @Override
    public void uncaughtException(Thread thread, final Throwable ex) {
        if (!handleException(ex) && defaultHandler != null) {
            //   defaultHandler.uncaughtException(thread, ex);
            //   defaultHandler.uncaughtException(thread, ex);
        } else {

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }

        }
        // 退出程序
//        android.os.Process.killProcess(android.os.Process.myPid());
//        System.exit(0);


    }


    /**
     * 自定义错误处理，收集错误信息，发送错误报告等操作均在此完成
     *
     * @param ex
     * @return true：如果处理了该异常信息；否则返回 false
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 使用 Toast 来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                showDialog(context, ex);
//                Toast.makeText(context, "很抱歉，程序出现异常，即将退出。"+ex.toString(), Toast.LENGTH_LONG).show();
//                new AlertDialog.Builder(context).setMessage(ex.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).show();
                Looper.loop();
            }
        }.start();

        WriteLogUtil.e(TAG, ex.toString());
        WriteLogUtil.e(TAG, getCrashDeviceInfo());
        WriteLogUtil.e(TAG, getCrashInfo(ex));
        ex.printStackTrace();
        // 收集设备参数信息
        // collectDeviceInfo(context);
        // 保存日志文件
        //  saveCrashInfo2File(ex);
        return true;
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);

            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }

        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 获取应用崩溃的详细信息
     *
     * @param ex
     * @return
     */
    public String getCrashInfo(Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.setStackTrace(ex.getStackTrace());
        ex.printStackTrace(printWriter);
        return writer.toString();
    }

    public String getCrashDeviceInfo() {
        String versionName = DeviceUtil.getVersionName(context);
        String model = Build.MODEL;
        String androidVersion = Build.VERSION.RELEASE;
        String manufacturer = Build.MANUFACTURER;
        return versionName + "  " +
                model + "  " +
                androidVersion + "  " +
                manufacturer;
    }

    private void showDialog(final Context context, Throwable ex) {
        final Dialog dialog;
        AlertDialog.Builder buder = new AlertDialog.Builder(context);
        buder.setTitle("温馨提示点击确定后重启APP!!!");
        buder.setMessage("由于发生了一个未知错误，应用已关闭，我们对此引起的不便表示抱歉！" +
                "" +
//                "您可以将错误信息上传到我们的服务器，帮助我们尽快解决该问题，谢谢！" +
                "错误信息:" + ex.toString());
      /*  buder.setPositiveButton("上传", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //上传处理---我这里没写，大家根据实际情况自己补上，我这里是一个Toast提示，提示内容就是我们要上传的信息
              //  Log.e(TAG, "---"+sbs.toString());
                Toast.makeText(mContext, sbs.toString(), Toast.LENGTH_LONG).show();
                new Thread(new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            Thread.sleep(3000);
                            //  mDefaultHandler.uncaughtException(thread, ex);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "error : ", e);
                        }
                        //退出程序
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(1);
                    }
                }).start();

            }
        });*/
        buder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                if (null != dialog) {
                    dialog.dismiss();
                }
                Intent intent = new Intent(context.getApplicationContext(), LoginActivity.class);
                PendingIntent restartIntent = PendingIntent.getActivity(
                        context.getApplicationContext(), 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
                //退出程序
                AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                        restartIntent); // 1秒钟后重启应用
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        });

        dialog = buder.create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.setCanceledOnTouchOutside(false);//设置点击屏幕其他地方，dialog不消失
        dialog.setCancelable(false);//设置点击返回键和HOme键，dialog不消失
        dialog.show();

        Log.i("PLog", "2");
    }
}
